package com.andnnl.list;

/**
 * Created by chenss on 2024/1/3.
 */

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;

public class WhiteListMatcher {
    private TrieNode root;

    private static class TrieNode {
        private Map<Character, TrieNode> children;
        private boolean isEndOfPattern;

        public TrieNode() {
            children = new HashMap<>();
            isEndOfPattern = false;
        }
    }

    public WhiteListMatcher() {
        root = new TrieNode();
    }

    public void addPattern(String pattern) {
        TrieNode current = root;
        for (char c : pattern.toCharArray()) {
            if (c == '*') {
                current.children.put(c, current); // '*' 匹配当前节点
            } else {
                current.children.putIfAbsent(c, new TrieNode());
                current = current.children.get(c);
            }
        }
        current.isEndOfPattern = true;
    }

    public boolean isMatch(String input) {
        Deque<TrieNode> stack = new ArrayDeque<>();
        Deque<Integer> indexStack = new ArrayDeque<>();
        stack.push(root);
        indexStack.push(0);

        while (!stack.isEmpty()) {
            TrieNode node = stack.pop();
            int index = indexStack.pop();

            if (index == input.length()) {
                if (node.isEndOfPattern) {
                    return true;
                }
                continue;
            }

            char c = input.charAt(index);
            if (node.children.containsKey(c)) {
                stack.push(node.children.get(c));
                indexStack.push(index + 1);
            }

            if (node.children.containsKey('*')) {
                stack.push(node.children.get('*'));
                indexStack.push(index);
                stack.push(node); // 继续匹配下一个字符
                indexStack.push(index + 1);
            }
        }

        return false;
    }
    public static void main(String[] args) {
        String[] whitelist = {
                "192.168.0.*",
                "*.example.com",
                "*.google.com",
                "10.0.0.1"
                // 添加更多白名单条目...
        };


        WhiteListMatcher matcher = new WhiteListMatcher();
        for (String pattern : whitelist) {
            matcher.addPattern(pattern);
        }
        System.out.println(matcher.toString());
        Stream.of("192.168.0.1", "192.168.1.2", "sub.example.com", "xddd.example.com")
                .forEach(ipOrDomain -> {
                    if (matcher.isMatch(ipOrDomain)) {
                        System.out.println(ipOrDomain+"\t Match found");
                    } else {
                        System.out.println(ipOrDomain+"\t No match found");
                    }
                });


    }
}
